package com.cictec.middleware.gps.engine.send;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.camel.CamelExecutionException;
import org.apache.camel.ProducerTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cictec.middleware.commons.spring.SpringContextHolder;
import com.cictec.middleware.commons.utils.Constants;
import com.cictec.middleware.commons.utils.PropertiesUtils;
import com.cictec.middleware.commons.utils.log.MultiLog;
import com.cictec.middleware.commons.utils.log.MultiLogFileNameUtils;
import com.cictec.middleware.commons.utils.log.MultiLogUtils;
import com.cictec.middleware.gps.engine.BusInstance;
import com.cictec.middleware.gps.engine.TimingPoint;

/**
 * 位置信息，存储、发送处理
 * @author Administrator
 *
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public class SendHandler {

	// private static Logger logger =
	// LoggerFactory.getLogger(SendHandler.class);

	// private static ProducerTemplate sendBusPostionToKafka=
	// SpringContextHolder.getBean("sendBusPostionToKafka");
	private static ProducerTemplate sendBusPostionToActivemq = SpringContextHolder.getBean("sendBusPostionToActivemq");
	private static ProducerTemplate sendBusPostionToStomp = SpringContextHolder.getBean("sendBusPostionToStomp");
	private static ProducerTemplate sendBusCanToStomp = SpringContextHolder.getBean("sendBusCanToStomp");
	private static ProducerTemplate sendBusChangeLineToStomp = SpringContextHolder.getBean("sendBusChangeLineToStomp");
	/** 发送至数据平台 */
	private static ProducerTemplate sendBusPostionToActivemqPlatform = SpringContextHolder.getBean("sendBusPostionToActivemqPlatform");
	private static ProducerTemplate sendBusPostionOrgToActivemq = SpringContextHolder.getBean("sendBusPostionOrgToActivemq");
//	private static ProducerTemplate sendBusPostionToES = SpringContextHolder.getBean("sendBusPostionToES");

	

	/**
	 * 推送数据 至 kafka
	 * @param busInstance
	 */
	public static void sendBusPostionToKafka(BusInstance busInstance){
//		String json = JSON.toJSONString(busInstance.getStatus());
		// kafka  直线图
		try {
//			sendBusPostionToKafka.sendBody(json);
		} catch (CamelExecutionException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 推送数据 至 apollo
	 * @param busInstance
	 */
	public static void sendBusPostionToStomp(BusInstance busInstance){
		
		if(!busInstance.isLineTypeExist()){
			busInstance.setLineType(Constants.VAL_LINE_NOT_SPEC);
		}
		
		Map dataMap = new HashMap();
		dataMap.putAll(busInstance.getAttributes());
		dataMap.put("warns", busInstance.getWarns());
		
		
		String json = JSON.toJSONString(dataMap);
		
//		String json = JSON.toJSONString(busInstance.getStatus());

		try {
			sendBusPostionToStomp.sendBody(json);
		} catch (CamelExecutionException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 车辆切换线路推送 更新
	 * @param busInstance
	 * @param tcr
	 */
	public static void sendBusChangeLineToStomp(String busUuid, String oldLineUuid, String newLineUuid) {

		Map<String, Object> body = new HashMap();

		body.put("busUuid", busUuid);
		body.put("oldLineUuid", oldLineUuid);
		body.put("newLineUuid", newLineUuid);


		try {
			sendBusChangeLineToStomp.sendBody(JSON.toJSONString(body));
		} catch (CamelExecutionException e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 推送数据 至 activemq 车辆预测使用
	 * @param busInstance
	 */
	public static void sendBusPostionToMq(BusInstance busInstance){
		
		try {
			
//			String json = JSON.toJSONString(busInstance.getStatus());
			// activemq app客户端使用
//			BusPositionMessage busPositionMessage = BusPositionConverter.convertToBusPositionMessage(busInstance.getStatus());
//			String busposition = JSON.toJSONString(busPositionMessage);
//			logger.debug("向mq中推送数据：" + busposition);
//			sendBusPostionToActivemq.sendBody(busposition);
			
			
			/*
			String rate = busInstance.getPositionRate();
			if (!PMSUtils.isEmpty(busInstance.getBusUuid())
					&& busInstance.isDevOnline() 
					&& !busInstance.isInStandBy() 
					&& !PMSUtils.isEmpty(busInstance.getStationSeq())
					&& !PMSUtils.isEmpty(busInstance.getStationName())
					&& 0 < Float.parseFloat(rate) && Float.parseFloat(rate) < 1) {
				logger.debug("发送到app数据 校验成功");
			}else{
				logger.debug("发送到app数据 校验失败");
			}
			if (!baseMessage.getDevOnline().equals("1") 
					|| baseMessage.getRate().equals("null")
					|| baseMessage.getRate().isEmpty() 
					|| baseMessage.getRate().equals(null)
					|| baseMessage.getSeq().isEmpty() 
					|| baseMessage.getSeq().endsWith(" ")
					|| baseMessage.getSeq().equals("null") 
					|| !baseMessage.getStandby().equals("0")
					|| baseMessage.getNextStation() == null 
					|| baseMessage.getNextStation().isEmpty()
					|| baseMessage.getNextStation().equals("null") 
					|| baseMessage.getNextStation().equals(" ")
					|| baseMessage.getRate().equals("1.0")) {
				
			}
			
			{"aheadDeparture":"null","frontTooClose":"0","msgType":"V1.1",
			"standby":"0","devCode":"13827092465","shift":"null","busSpeed":"0.00","counrse":"26","devOnline":"1",
			"overSpeed":"null","colsedAlarms":"","trip":"null","delayDeparture":"null","rate":"","frontTooFar":"0","lineUuid":"1602",
			"startTime":"null","allAlarms":"7","busUuid":"-378771239","lat":"22.6310889734183","seq":"null","devUuid":"-1779112731","direction":"1",
			"lng":"113.06483441245675","backTooClose":"0","uploadTime":"2017-05-03 11:19:53:000","dispatchStatus":"0","buselfcode":"null","busPlate":"粤J42827",
			"phone":"null","positionOvertake":"0","inStation":"null","operStatus":"0","driverName":"null",
			"gatherTime":"2017-05-03 11:19:53:000","nextStation":"null","willDeparture":"null"}

"seq":"null"
"inStation":"null"
"nextStation":"null"
			 */

			
			
			
			/**
			 * 
			 */
			Map headers = new HashMap();
			headers.put(Constants.HED_MSG_TYPE, busInstance.getMsgType());
			headers.put(Constants.HED_DEV_UUID, busInstance.getDevUuid());
			headers.put(Constants.HED_DEV_CODE, busInstance.getDevCode());
			headers.put(Constants.HED_UPLOAD_TIME, busInstance.getUploadTime());							// 数据上传时间
			headers.put(Constants.MSG_INFO_POSITION_GATHER_TIME, busInstance.getGatherTime());				// gps数据采集时间yyyy-mm-dd hh:mi:ss:SSS
			headers.put(Constants.HED_BUS_PALTE, busInstance.getBusNumber());										// 车牌号
			headers.put(Constants.HED_BUS_UUID, busInstance.getBusUuid());											// 车辆uuid
			headers.put(Constants.HED_BUS_SELF_CODE, busInstance.getBusSelfCode());									// 车辆自编号
			headers.put(Constants.MSG_INFO_POSITION_STATION_SEQ, busInstance.getStationSeq());				// 站点序号
			
			busInstance.setAttribute(Constants.MSG_INFO_POSITION_STATION_SEQ, busInstance.getStationSeq());
			busInstance.setAttribute(Constants.MSG_INFO_LOGIN_STATUS, busInstance.getLoginStatus());
			busInstance.setAttribute(Constants.MSG_INFO_POSITION_RATE, busInstance.getPositionRate());
			busInstance.setAttribute(Constants.MSG_INFO_POSITION_STANDBY_FLAG, busInstance.getStatusStandBy());
			busInstance.setAttribute(Constants.MSG_INFO_POSITION_LINE_UUID, busInstance.getLineUuid());
			
			busInstance.setAttribute(Constants.MSG_INFO_POSITION_GATHER_TIME, busInstance.getUploadTime());
			busInstance.setAttribute(Constants.MSG_INFO_POSITION_BUS_STATUS, busInstance.getStatusInOperateTime());
			busInstance.setAttribute(Constants.MSG_INFO_POSITION_DIRECTION, busInstance.getLineType());
			
//			logger.debug("headers:" + JSON.toJSONString(headers));
//			logger.debug("body:" + JSON.toJSONString(busInstance.getStatus()));
			
			String logPath = MultiLogFileNameUtils.getMqLogName(busInstance.getDevCode() + "-" +busInstance.getBusNumber());
			MultiLog log = MultiLogUtils.getMultiLog(logPath);
			log.debug("header:{}, bodys:{}", headers, busInstance.getAttributes());
			
//			sendBusPostionToActivemq.sendBody(busInstance.getStatus());
			sendBusPostionToActivemq.sendBodyAndHeaders(busInstance.getAttributes(), headers);
		} catch (CamelExecutionException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 推送数据 至 activemq 数据转发平台
	 * @param busInstance
	 */
	public static void sendBusPostionToMqPlatform(BusInstance busInstance){
		
		// 是否发送数据到转发平台
		boolean flag = PropertiesUtils.getBoolean("system.parameter.sendmq.platform", false);
		if(!flag){
			return;
		}
		
		try {
			
			sendBusPostionToActivemqPlatform.sendBody(busInstance.getAttributes());
		} catch (CamelExecutionException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 推送can总线消息数据
	 * @param busInstance
	 */
	public static void sendBusCanToStomp(BusInstance busInstance, String jsonData){
		
		JSONObject json = JSONObject.parseObject(jsonData);
		
		Map<String, Object> body = new HashMap();
		
		body.put("busUuid", busInstance.getBusUuid());
		body.put("devUuid", busInstance.getDevUuid());
		body.put("lineUuid", busInstance.getLineUuid());
		
		body.put("speed", json.getString("speed"));
		body.put("mileage", json.getString("mileage"));
		
		try {
			
//			String logPath = MultiLogFileNameUtils.getApolloLogName(busInstance.getDeviceCode() + "-" +busInstance.getBusNumber());
//			MultiLog log = MultiLogUtils.getMultiLog(logPath);
//			log.debug(JSON.toJSONString(body));
			
			sendBusCanToStomp.sendBody(JSON.toJSONString(body));
		} catch (CamelExecutionException e) {
			e.printStackTrace();
		}
	}
	
	private static ProducerTemplate sendLineAverageSpeedToStomp = SpringContextHolder.getBean("sendLineAverageSpeedToStomp");
	/**
	 * 推送线路平均速度到ws中
	 * @param map
	 */
	public static void sendLineAverageSpeedToStomp(Map map){
	
		try {
			sendLineAverageSpeedToStomp.sendBody(JSON.toJSONString(map));
		} catch (CamelExecutionException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 异步GPS位置数据
	 * @param date		数据日期
	 * @param devCode	设备编号
	 * @param object	数据对象
	 */
	public static void sendBusPostionSaveFromSeda(String date, String devCode, Object object, String redisKeyTM){
		
		if (object == null) {
			return;
		}
		
		try {
			Map data = new HashMap();
			data.put("devCode", devCode);
			data.put("date", date);
			if(redisKeyTM != null){
				data.put("redisKeyTM", redisKeyTM);
			}
			
			List<TimingPoint> list = new ArrayList<TimingPoint>();
			if(object instanceof ArrayList){
				data.put("jsonType", "list");
				List<TimingPoint> positionList = (List<TimingPoint>) object;
				list.addAll(positionList);
			}else{
				data.put("jsonType", "map");
				TimingPoint timingPoint = (TimingPoint) object;
				if(timingPoint.getAttributes().size() > 0){
					list.add(timingPoint);
				}
			}
			data.put("jsonData", JSON.toJSONString(list));
			
			sendBusPostionOrgToActivemq.sendBody(data);
		} catch (CamelExecutionException e) {
			e.printStackTrace();
		}
	}
	
	
	public static void sendBusPostionSaveFromSeda(String date, String devCode, TimingPoint timingPoint, String redisKeyTM){
		
		if (timingPoint == null) {
			return;
		}
		
		try {
			Map data = new HashMap();
			data.put("devCode", devCode);
			data.put("date", date);
			if(redisKeyTM != null){
				data.put("redisKeyTM", redisKeyTM);
			}
			
			List<TimingPoint> list = new ArrayList<TimingPoint>();
			list.add(timingPoint);
			data.put("jsonData", JSON.toJSONString(list));
			
			sendBusPostionOrgToActivemq.sendBody(data);
		} catch (CamelExecutionException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 保存车辆位置信息、进出站到ES【mq异步】
	 * @param map
	 */
//	public static void sendBusPostionToES(Map map){
//		// Map map = new HashMap();
//		// map.put("date", date);
//		// map.put("busUuid", busUuid);
//		// map.put("busNumber", busNumber);
//		// map.put("deleteEnterOut", deleteEnterOutList);
//		// map.put("saveEnterOut", enterOutESModelList);
//		// map.put("savePosition", positionESModelList);
//		sendBusPostionToES.sendBody(map);
//	}
}
